<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { getBannerAPI, getCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { SunGuessInstance } from '@/components/component'
import PageSkeleton from './components/PageSkeleton.vue'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])
// 猜你喜欢组件实例 类型需要定义SunGuessInstance
const guessRef = ref<SunGuessInstance>()
// 下拉状态
const isDownDrag = ref<boolean>(false)
// 加载状态
const isLoading = ref<boolean>(false)
// 首页轮播图
const getBannerFun = async () => {
  const res = await getBannerAPI()
  bannerList.value = res.result
}
// 首页分类
const getCategoryFun = async () => {
  const res = await getCategoryAPI()
  categoryList.value = res.result
}
// 首页热门推荐
const getHomeHotFun = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
// 滚动触底
const onScrolltolower = () => {
  guessRef.value?.getHomeGoodsGuessLikeFun()
}
// 下拉刷新时触发函数
const onRefresherrefresh = async () => {
  // 开始动画
  isDownDrag.value = true
  // 猜你喜欢使子组件，需要重置条件再调用接口
  guessRef.value.refreshData()
  // Promise.all可使请求同时发送
  await Promise.all([
    getBannerFun(),
    getCategoryFun(),
    getHomeHotFun(),
    guessRef.value?.getHomeGoodsGuessLikeFun(),
  ])
  // 加载完关闭下拉动画
  isDownDrag.value = false
}
// 初始加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerFun(), getCategoryFun(), getHomeHotFun()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器:可进行y轴即竖向滚动（一定要设置高度：除了自定义导航栏都滚动） ; @scrolltolower=""要做触底处理; @refresher-enabled="true"开启下拉刷新 refresherrefresh=""下拉刷新时触发-->
  <scroll-view
    refresher-enabled
    scroll-y
    :refresher-triggered="isDownDrag"
    class="scroll-view"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
  >
    <!-- 骨架屏显示与否取决于加载是否完成 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <SunSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 ref绑定组件 -->
      <SunGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: aliceblue;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
